<?php
namespace App\Services\Core\Store\Baixing;

use App\Helpers\RestResponseFactory;
use App\Helpers\RestUtils;
use App\Models\Factory\ThirdapilogFactory;
use App\Models\Factory\UserLoanQuotaFactory;
use App\Models\Orm\Identity;
use App\Models\Orm\Province;

/**
 * 百姓网对接服务
 * Class BaixingService
 * @package App\Services\Core\Store\Baixing
 */
class BaixingService
{

    /**
     * @param $userphone
     * @return bool
     */
    public static function filterUser($userphone)
    {
        $user_identity = Identity::where('userphone',$userphone)->first();
        if(empty($user_identity))
        {
            return RestResponseFactory::ok(RestUtils::getStdObj(),1005,1005,RestUtils::getErrorMessage(1005));
        }
        self::Send($user_identity);

    }


    /**
     * 发送数据到三方
     * @return mixed
     */
    public static function Send($data)
    {
        //查询出贷款的金额
        $money = BaixingStrategy::getLoanAmountNum(self::getUserLoadMoney($data['userphone']));
        //获取发送的城市
        $city  = self::getOpenCity($data['city']);
        //判断用户是否有车
        $car   = self::getHasCar($data['has_car']);
        //根据贷款金额城市车辆判断是否发送数据
        if(($money>3) && ($city == 1) && ($car ==1)) {
            $params = [
                'channelCode'             => BaixingConfig::$channelCode,     //渠道标识码
                'name'                    => $data['name'],                                //用户姓名
                'mobile'                  => $data['userphone'],                        //用户手机号
                'sign'                    => md5((BaixingConfig::$channelCode) . $data['userphone']),               //签名
                'loanAmount'              => BaixingStrategy::getLoanAmountNum(self::getUserLoadMoney($data['userphone'])),                                //贷款金额
                'profession'              => $data['professional'],                                //职业
                'haveFund'                => self::getHasAccumulationFund($data['accumulation_fund']),                                  //是否有公积金
                'haveSecurity'            => ($data['social_security'] == 1) ? 1 : 0,                              //是否有社保
                'propertyType'            => ($data['has_house'] == 1) ? 0 : 11,                              //房产类型
                'carType'                 => self::getHasCar($data['has_car']),                                   //是否有车
                'idCard'                  => '',                                   //身份证号(可为空)
                'haveCommercialInsurance' => ($data['has_issurance'] == 1) ? 1 : 0,                   //是否购买商业保险
                'haveCreditCard'          => ($data['is_credit'] == 2) ? 1 : 0,                            //是否有信用卡
                'province'                => $data['province'],                                //省份 (汉字)
                'city'                    => $data['city'],                                     //城市 （汉字）
                'gender'                  => ($data['sex'] == 1) ? 0 : 1,                                    //性别
                'birth'                   => $data['birthday'],                          //出生日期
                'age'                     => $data['age'],                                      //年龄
                'salaryType'              => self::getWage($data['wage']),                                //发薪方式
                'monthlySalary'           => $data['month_money'],                             //月薪
                'isAtom'                  => '',                                   //是否有微粒贷
                'remark'                  => ''                                 //备注信息
            ];
            $sendParams = json_encode($params,JSON_UNESCAPED_UNICODE);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, BaixingConfig::$url_online);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($sendParams)
            ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $sendParams);

            $res = curl_exec($ch);
            curl_close($ch);

            $response = json_decode($res,true);

            // 创建推送日志
            $createlogdata = array(
                'uid'          => $data['uid'],
                'userphone'    => $data['userphone'],
                'code'         => '200',
                'message'      => $response['message'],
                'status'       => ($response['status'] == 'SUCCESSED') ? 1 : 2,
                'type'         => 9,
                'created_at'   => date('Y-m-d H:i:s')
            );
            ThirdapilogFactory::createlog($createlogdata);
        }
    }




    /**
     * @param $car
     * @return int
     */
    public static function getHasCar($car)
    {
        if($car == 2 || $car == 3){
            return 1;
        }else{
            return 0;
        }
    }


    /**
     * 是否有公积金
     * @param $accumulationFund
     * @return int
     */
    public static function getHasAccumulationFund($accumulationFund)
    {
        if($accumulationFund == 2 || $accumulationFund == 3){
            return 1;
        }else{
            return 0;
        }
    }


    /**
     * 薪资发放方式
     * @param $wage
     * @return int
     */
    public static function getWage($wage)
    {
        if($wage == 1){
            return 0;
        }elseif($wage == 2){
            return 1;
        }
        return 0;
    }




    /**
     * 获取三方开放的城市
     * @param $city
     * @return bool
     */
    public static function getOpenCity($city)
    {
        switch($city){
            case mb_substr($city,0,2) == '北京':
                return true;
                break;
            case mb_substr($city,0,2) == '上海':
                return true;
                break;
            case mb_substr($city,0,2) =='深圳':
                return true;
                break;
            case mb_substr($city,0,2) =='广州':
                return true;
                break;
            case mb_substr($city,0,2) =='佛山':
                return true;
                break;
            case mb_substr($city,0,2) =='南京':
                return true;
                break;
            case mb_substr($city,0,2) =='武汉':
                return true;
                break;
            case mb_substr($city,0,2) =='杭州':
                return true;
                break;
            default:
                return false;
                break;
        }
    }

    /**
     * @param $userphone
     * @return float
     */
    public static function getUserLoadMoney($userphone)
    {
        // 贷款额度（单位：万）
        $LoanAmount = UserLoanQuotaFactory::getUserLoanQuota($userphone);
        $Amount = $LoanAmount != false&&isset($LoanAmount['quota_money']) ? $LoanAmount['quota_money'] : 0;
        return round($Amount/10000);
    }

}
